﻿using System;
using MediatR;
using System.Collections.Generic;
using Casamiel.Domain;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.MWeb;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.Extensions.Options;
using Casamiel.Common;
using Newtonsoft.Json;
using System.Linq;

using Casamiel.Domain.Request;
using Newtonsoft.Json.Linq;
using Enyim.Caching;

namespace Casamiel.Application.Commands.Waimai.V2
{
	/// <summary>
	/// Get product by identifier store identifier command handler.
	/// </summary>
	public sealed class GetProductByIdStoreIdCommandHandler : BaseCommandHandler, IRequestHandler<GetProductByIdStoreIdCommand, BaseResult<GoodsProductBaseRsp>>
	{
		private readonly IMemcachedClient _memcachedClient;
		private readonly IMbrStoreRepository _mbrStoreRepository;
		/// <summary>
		/// Initializes a new instance of the
		/// <see cref="T:Casamiel.Application.Commands.GetProductByIdStoreIdCommandHandler"/> class.
		/// </summary>
		/// <param name="mbrStoreRepository">Mbr store repository.</param>
		/// <param name="netICService">Net ICS ervice.</param>
		/// <param name="httpClientFactory">Http client factory.</param>
		/// <param name="settings">Settings.</param>
		/// <param name="memcachedClient"></param>
		public GetProductByIdStoreIdCommandHandler(IMbrStoreRepository mbrStoreRepository, INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings, IMemcachedClient memcachedClient) : base(netICService, httpClientFactory, settings)
		{
			_mbrStoreRepository = mbrStoreRepository;
			_memcachedClient = memcachedClient;
		}

		/// <summary>
		/// Handle the specified request and cancellationToken.
		/// </summary>
		/// <returns>The handle.</returns>
		/// <param name="request">Request.</param>
		/// <param name="cancellationToken">Cancellation token.</param>
		public async Task<BaseResult<GoodsProductBaseRsp>> Handle(GetProductByIdStoreIdCommand request, CancellationToken cancellationToken)
		{
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var storeinfo = await _mbrStoreRepository.GetByStoreIdAsync<ICasaMielSession>(request.StoreId).ConfigureAwait(false);
			if (storeinfo == null) {
				return new BaseResult<GoodsProductBaseRsp>(null, 999, "storeid 有误");
			}
			var url = "TakeOut/v3/Goods/GetById";//根据商品Id和门店Id获取商品信息

			if (request.Version == "pre") {
				url = "Pred/v3/Goods/GetById";
			}
			var result = await PostThirdApiAsync<GoodsProductBaseRsp>(url, JsonConvert.SerializeObject(new { storeId = request.StoreId, productId = request.ProductId }))
				.ConfigureAwait(false);
			//var rsp = JsonConvert.DeserializeObject<JObject>(result);
			if (result.Code != 0) {
				return result;
				// return new BaseResult<Goods_ProductBaseRsp>(null, 9999, rsp["resultRemark"].ToString());
			}
			//List<TPP_Goods_DrinksSkuIdRsp> listskus;// = await GetDrinkSkus().ConfigureAwait(false);

			//var cakey = base.MemcachedPre+ "DrinkSkus";
			//var datas = await _memcachedClient.GetAsync<List<TPP_Goods_DrinksSkuIdRsp>>(cakey).ConfigureAwait(false);
			//if (!datas.Success) {
			//	listskus = await GetDrinkSkus().ConfigureAwait(false);
			//	await _memcachedClient.SetAsync(cakey, listskus, 300).ConfigureAwait(false);
			//} else {
			//	listskus = datas.Value;
			//}

			var GoodsBase = result.Content;// JsonConvert.DeserializeObject<Goods_ProductBaseRsp>(rsp["data"].ToString());
			//if (GoodsBase != null) {
			//	var req = new ProductStockQueryReq { datasource = request.DataSource, shopid = storeinfo.RelationId, product = new List<Domain.Request.ProductStockReq>() };
			//	if (GoodsBase.GoodsList.Any()) {
			//		foreach (var item in GoodsBase.GoodsList) {
			//			req.product.Add(new ProductStockReq { pid = $"{item.RelationId}" });
			//		}
			//		var zmodel = await NetICService.Productstockquery(req).ConfigureAwait(false);
			//		if (zmodel != null) {
			//			var _count = GoodsBase.GoodsList.Count;
			//			for (int i = 0; i < _count; i++) {
			//				var t = zmodel.product.Find(a => a.pid == $"{GoodsBase.GoodsList[i].RelationId}");
			//				if (listskus.Any(c => c.GoodsRelationId == GoodsBase.GoodsList[i].RelationId)) {
			//					GoodsBase.GoodsList[i].StockQuentity = 99;
			//				} else {
			//					if (t != null && t.icprice > 0) {
			//						GoodsBase.GoodsList[i].Price = t.originprice;
			//						GoodsBase.GoodsList[i].CostPrice = t.icprice;
			//						if (storeinfo.IsLimitStock == 1) {
			//							GoodsBase.GoodsList[i].StockQuentity = 100;
			//						} else {
			//							//if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30")))
			//							//{
			//							//    //if (t.count > 0)
			//							//    //{
			//							//    //    int a = await _storeService.GetGoodsQuantityByPidAsync<ICasaMielSession>(item.RelationId, DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30")));
			//							//    //    item.StockQuentity = t.count - a;
			//							//    //}
			//							//    //else
			//							//    //{
			//							//    item.StockQuentity = t.count;
			//							//    //}
			//							//}
			//							//else
			//							//{

			//							GoodsBase.GoodsList[i].StockQuentity = t.count;
			//							//}
			//						}
			//					}
			//				}
			//			}
			//		}
			//	}

			//}
			return new BaseResult<GoodsProductBaseRsp>(GoodsBase, 0, "");
		}
	}
}
